package com.jic.manager.impl;

import com.alibaba.fastjson.JSONArray;
import com.jic.common.base.vo.Page;
import com.jic.common.base.vo.PageResult;
import com.jic.common.base.vo.RestResult;
import com.jic.common.redis.RedisClientTemplate;
import com.jic.enums.RedisKey;
import com.jic.manager.entity.*;
import com.jic.manager.enums.SmsEnums;
import com.jic.manager.mapper.*;
import com.jic.manager.request.SysUserRequest;
import com.jic.manager.request.UccUserRequest;
import com.jic.manager.request.UpdateUccUserStatusRequest;
import com.jic.manager.request.UserAuthorRequest;
import com.jic.manager.response.UccUserResponse;
import com.jic.manager.service.MerchantService;
import com.jic.manager.service.SysUserDeptService;
import com.jic.manager.service.SysUserService;
import com.jic.manager.utils.MD5Utils;
import com.jic.manager.utils.RedisManager;
import com.jic.manager.utils.SmsUtils;
import com.jic.manager.utils.UccHttpUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.core.util.UuidUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

/**
 * 后台用户管理
 * @author : 
 * @email : 
 * @since : 2020-02-25 05:29:32
 * @version : v1.0.0
 */
@Slf4j
@Service
public class SysUserServiceImpl implements SysUserService{

    @Resource
    private SysUserMapper sysUserMapper;
    @Resource
    private MestoreMapper mestoreMapper;
    @Resource
    private UccHttpUtils uccHttpUtils;
    @Resource
    private SysUserDeptMapper sysUserDeptMapper;
    @Resource
    private SysDeptMapper sysDeptMapper;
//    @Resource
//    private RedisClientTemplate redisClientTemplate;
    @Resource
    private RedisManager redisManager;
    @Resource
    private SysRoleUserMapper sysRoleUserMapper;

    @Resource
    private SmsUtils smsUtils;

    @Override
    public long insert(SysUser sysUser) {
        long flag = sysUserMapper.insert(sysUser);
        return flag;
    }

    @Override
    public long delete(Long id) {
        return sysUserMapper.delete(id);
    }

    @Override
    public long update(SysUser sysUser) {
        return sysUserMapper.update(sysUser);
    }

    @Override
    public SysUser queryByPrimaryKey(Long id){
        return sysUserMapper.queryByPrimaryKey(id);
    }

    @Override
    public List<SysUser> query(SysUser sysUser){
        return sysUserMapper.query(sysUser);
    }

    @Override
    public PageResult<SysUser> queryPage(SysUser sysUser, Page pageQuery) {
        //计算下标
        int startIndex = (pageQuery.getStart() - 1) * pageQuery.getLimit();
        List<SysUser> list = sysUserMapper.queryPage(startIndex, pageQuery.getLimit(), sysUser);
        long count = sysUserMapper.queryPageCount(sysUser);
        PageResult pageResult = new PageResult();
        pageResult.setRows(list);
        pageResult.setTotal(count);
        return pageResult;
    }

    @Override
    public RestResult<String> editSysUser(SysUserRequest sysUserRequest) {
        try{
            SysUser sysUser = new SysUser();
            BeanUtils.copyProperties(sysUserRequest,sysUser);
            Integer type = sysUser.getType();
            if(type == 2){
                Mestore mestore = mestoreMapper.queryByPrimaryKey(sysUser.getStoreId());
                sysUser.setDeptId(mestore.getMerchantId());
            }
            if (sysUser.getId() != null && sysUser.getId() != 0){
                //修改
                SysUser sysUserVo = sysUserMapper.queryByPrimaryKey(sysUser.getId());
                if (StringUtils.isNotEmpty(sysUser.getPassword())){
                    sysUser.setPassword(MD5Utils.md5(sysUser.getPassword(),sysUserVo.getFlag()));
                }
                sysUser.setUpdater(sysUserRequest.getAdminOperate().getOperator());
                sysUser.setUpdaterName(sysUserRequest.getAdminOperate().getOperateName());
                sysUserMapper.update(sysUser);
            }else{
                sysUser.setFlag(UUID.randomUUID().toString());
                //新增
                sysUser.setDeleteFlag(0);
                sysUser.setPassword(MD5Utils.md5(sysUser.getPassword(),sysUser.getFlag()));
                sysUserMapper.insert(sysUser);
            }
            return RestResult.success("修改用户成功");
        }catch (Exception e){
            // TODO
            e.printStackTrace();
           return RestResult.error("9999",e.getLocalizedMessage());
        }
    }

    @Override
    public RestResult<String> deleteSysUser(SysUserRequest sysUserRequest) {
        try {
            String ids = sysUserRequest.getIds();
            if (StringUtils.isEmpty(ids)){
                throw new RuntimeException("必传参数为空 ids");
            }
            String[] idsStr = ids.split(",");
            for (int i = 0; i < idsStr.length; i++) {
                sysUserMapper.delete(Long.valueOf(idsStr[i]));
            }
            return RestResult.success("删除成功");
        }catch (Exception e){
            // TODO
            e.printStackTrace();
            return RestResult.error("9999",e.getLocalizedMessage());
        }
    }

    @Override
    public Long insertSysUser(SysUser sysUser) throws Exception {
        String password = sysUser.getPassword();
        String account = sysUser.getAccount();
        String mobile = sysUser.getMobile();
        if (StringUtils.isEmpty(password) || StringUtils.isEmpty(account) || StringUtils.isEmpty(mobile)){
            throw new RuntimeException("必传参数为空");
        }
        String uuid = UUID.randomUUID().toString();
        sysUser.setFlag(uuid);
        sysUser.setPassword(MD5Utils.md5(sysUser.getPassword(),uuid));
        sysUserMapper.insert(sysUser);
        return sysUser.getId();
    }

    @Override
    public RestResult<List<UccUserResponse>> getUccUserListByEmployinfo(UccUserRequest uccUserRequest) {
        try {
            List<UccUserResponse> uccUserResponseList = uccHttpUtils.getUccUserListByEmployinfo(uccUserRequest);
            return RestResult.success(uccUserResponseList);
        }catch (Exception e){
            log.error("查询uuc用户list失败+++++++>>>>>{}",e.getMessage());
            return RestResult.error("9999","服务器错误...");
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public RestResult<Boolean> saveUserInfoAuthor(UserAuthorRequest userAuthorRequest) throws Exception{

            //根据账号查询用户是否存在
            List<SysUser> sysUserList = sysUserMapper.query(new SysUser() {{
                setAccount(userAuthorRequest.getAccount());
                setDeleteFlag(0);
            }});
            if (CollectionUtils.isNotEmpty(sysUserList)){
                return RestResult.error("9999","该人员已被添加，不能重复添加");
            }
            //保存用户信息
            SysUser sysUser = new SysUser();
            sysUser.setNumber(userAuthorRequest.getNumber());
            sysUser.setAccount(userAuthorRequest.getAccount());
            sysUser.setUsername(userAuthorRequest.getUsername());
            sysUser.setRoleid(userAuthorRequest.getRoleid());
            sysUser.setDeptId(userAuthorRequest.getDeptId());
            sysUser.setLname(userAuthorRequest.getDeptName());
            sysUser.setMobile(userAuthorRequest.getMobile());
            sysUser.setCreator(userAuthorRequest.getAdminOperate().getOperator());
            sysUser.setFlag(UUID.randomUUID().toString());
            sysUser.setDeleteFlag(0);
            sysUser.setType(userAuthorRequest.getType());
            sysUser.setPassword(MD5Utils.md5(userAuthorRequest.getPassword(),sysUser.getFlag()));
            sysUser.setStatus(1);
            sysUserMapper.insert(sysUser);

            sysRoleUserMapper.insert(new SysRoleUser(){{
                setRoleid(userAuthorRequest.getRoleid());
                setUserid(sysUser.getId());
                setStatus("0");
            }});
            return RestResult.success(true);
    }

    /**
     * 编辑用户数据及数据权限
     * @param userAuthorRequest
     * @return
     * @throws Exception
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public RestResult<Boolean> updateUserInfoAuthor(UserAuthorRequest userAuthorRequest) throws Exception {
        //根据账号查询用户是否存在
        List<SysUser> sysUserList = sysUserMapper.query(new SysUser() {{
            setId(userAuthorRequest.getId());
            setDeleteFlag(0);
        }});
        if (CollectionUtils.isEmpty(sysUserList)){
            return RestResult.error("9999","用户数据不存在");
        }
        //保存用户信息
        SysUser sysUser = new SysUser();
        sysUser.setNumber(userAuthorRequest.getNumber());
        sysUser.setUsername(userAuthorRequest.getUsername());
        sysUser.setRoleid(userAuthorRequest.getRoleid());
        sysUser.setDeptId(userAuthorRequest.getDeptId());
        sysUser.setLname(userAuthorRequest.getDeptName());
        sysUser.setMobile(userAuthorRequest.getMobile());
        sysUser.setCreator(userAuthorRequest.getAdminOperate().getOperator());
        sysUser.setDeleteFlag(0);
//        sysUser.setAccount(userAuthorRequest.getAccount());
//        if(!userAuthorRequest.getPassword().equals(sysUserList.get(0).getPassword())){
//            sysUser.setPassword(MD5Utils.md5(userAuthorRequest.getPassword(),sysUser.getFlag()));
//            sysUser.setFlag(UUID.randomUUID().toString());
//        }
        sysUser.setStatus(1);
        sysUser.setId(sysUserList.get(0).getId());
        sysUserMapper.update(sysUser);

        //判断用户角色是否改变
        if(!userAuthorRequest.getRoleid().equals(sysUserList.get(0).getRoleid())){
            SysRoleUser sysRoleUser =  sysRoleUserMapper.queryByUserIdRoleId(sysUser.getId(), userAuthorRequest.getRoleid());
            sysRoleUserMapper.update(new SysRoleUser(){{
                setRoleid(userAuthorRequest.getRoleid());
                setUserid(sysUser.getId());
                setId(sysRoleUser.getId());
            }});
        }

        sysUserDeptMapper.deleteByUserId(sysUser.getId());
        return RestResult.success(true);
    }

    @Override
    public RestResult<Boolean> updateUccUserStatus(UpdateUccUserStatusRequest updateUccUserStatusRequest) {
        try {
            //查询当前账号状态
            SysUser sysUser = sysUserMapper.queryByPrimaryKey(updateUccUserStatusRequest.getUserId());
            if (null == sysUser || sysUser.getDeleteFlag().equals(1)){
                return RestResult.error("9999","当前账号不存在");
            }
            sysUserMapper.update(new SysUser(){{
                setStatus(updateUccUserStatusRequest.getStatus());
                setId(updateUccUserStatusRequest.getUserId());
            }});
            //如果停用 删除redis登录缓存
            if(updateUccUserStatusRequest.getStatus() == 0){
                Set<String> keys = redisManager.getKeys(RedisKey.UUC_TOKEN.getName()+updateUccUserStatusRequest.getUserId());
                log.info("==================================>>>>>{}", JSONArray.toJSONString(keys));
                if (CollectionUtils.isNotEmpty(keys)){
                    for (Iterator iterator = keys.iterator(); iterator.hasNext();) {
                        String string = (String) iterator.next();
                        System.out.println(string);
                        redisManager.del(string);
                    }
                }
            }
            return RestResult.success(true);
        }catch (Exception e){
            log.error("修改账号状态异常====>>>>>>{}",e.getMessage());
            return RestResult.error("9999","服务器错误...");
        }
    }

    @Override
    public List<String> userPhone(Date date) {
        List<String> list = sysUserMapper.userPhone(date);
        return list;
    }
}